require 'digest'

class Client < ActiveRecord::Base
  validates_presence_of :name, :email
  attr_protected :access_token
  has_many :tickets, :include => :workflows

  # add user
  def self.add_user (attr)
    client = self.new
    client.name = attr[:name]
    client.email = attr[:email]
    client.tickets.build({
                              :title => attr[:title],
                              :question => attr[:question],
                              :department_id => attr[:department],
                              :parent_id => proc{ result = Ticket.find_by_parent_id(nil); if result.id.nil? then 1 else result.id end }.call
                          }).save
    if client.save
      access_token = Digest::SHA1.hexdigest(client.email.to_s + client.id.to_s)
      client.update_attribute('access_token', access_token)
    end
    return client
  end
end